from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout,CMakeDeps
from conan.tools.files import copy, get,chdir
from conan.tools.gnu import Autotools, AutotoolsToolchain
import os
class SampleRecipe(ConanFile):
    name = "libzmq"  # name of the package
    version = "4.3.5"  # version of the package, assuming a version for illustration
    user = "thirdparty"
    channel = "development"
    license = "LGPLv3 with static linking exception"  # license of the package, ZeroMQ uses this license
    author = "ZeroMQ maintainers"  # author of the package, referring to the group maintaining ZeroMQ
    url = "https://github.com/zeromq/libzmq"  # url of the package, ZeroMQ's GitHub URL
    description = "High-performance asynchronous messaging library."
    topics = ("messaging", "communication", "asynchronous", "zmq")  # topics of the package, related to ZeroMQ
    settings = "os", "compiler", "build_type", "arch"  # settings of the package
    options = {"shared": [True, False], "fPIC": [True, False],"usr_mode" : ["cmake", "autotools"]}  # options of the package
    default_options = {"shared": True, "fPIC": True , "usr_mode" : "cmake"}  # default options of the package
    # exports_sources = "expat/*" 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.build_mode = "cmake"   
        self.work_dir = ""
    def source(self):# two step
    #     # Please, be aware that using the head of the branch instead of an immutable tag
    #     # or commit is a bad practice and not allowed by Conan
        get(self, "https://github.com/zeromq/libzmq/releases/download/v4.3.5/zeromq-4.3.5.zip",
                  strip_root=True)
        self.output.info("self.source_folder  = " + self.source_folder)
        # 如果cmakelist.txt在subfolder文件夹下,则需要将expat文件夹移动到source_folder下
#        self.work_dir = os.path.join(self.source_folder, "subfolder")
    # def requirements(self):
    #     self.requires("fmt/10.2.1")

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC # Windows does not require -fPIC flag

    def layout(self):# first step   
        cmake_layout(self)
        self.output.info("self.folders.source = " + self.folders.source)    
        #self.folders.source = os.path.join(self.folders.source, "expat")

    def generate(self):# third step
        self.detect_build_system()
        self.output.info("generate pwd = " + os.getcwd())
        if self.build_mode == "cmake":
            tc = CMakeToolchain(self)
            tc.generate()
            deps = CMakeDeps(self)
            deps.generate()
        elif self.build_mode == "autotools":
            tc = AutotoolsToolchain(self)
            tc.generate()
        else:
            raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")

    def build(self):
        self.output.info(" build pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            self.output.info("执行 CMake 构建流程")
            cmake = CMake(self)
            if self.work_dir:
                cmake.configure(build_script_folder=self.work_dir)
            else:
                cmake.configure(variables={"WITH_LIBBSD": "OFF"})
            cmake.build()
        elif self.build_mode == "autotools":    
            with chdir(self, self.source_folder):
                autotools = Autotools(self)
                autotools.configure(args=["--prefix={}".format(self.package_folder)])
                autotools.make()
    def package(self):
        self.output.info(" package pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            cmake = CMake(self)
            cmake.install()
        elif self.build_mode == "autotools":  
            with chdir(self, self.source_folder):
                autotools = Autotools(self)
                autotools.install()
            
    # def package_info(self):
    #     self.cpp_info.names["cmake_find_package"] = "EXPAT"
    #     self.cpp_info.names["cmake_find_package_multi"] = "EXPAT"
    #     self.cpp_info.components["libexpat"].names["cmake_find_package"] = "EXPAT"
    #     self.cpp_info.components["libexpat"].names["cmake_find_package_multi"] = "EXPAT"
    #     self.cpp_info.components["libexpat"].libs = ["expat"]
    def detect_build_system(self):
        cmake_file_path = os.path.join(self.source_folder, "CMakeLists.txt")
        
        if os.path.exists(cmake_file_path):
            self.output.info("CMakeLists.txt exists: Yes")
        elif os.path.exists(os.path.join(self.source_folder, "configure")):
            self.build_mode = "autotools"
            self.output.info("configure exists: Yes")
            # 如果不加权限,configure()方法有可能无法执行
            os.chmod(os.path.join(self.source_folder, "configure"), 0o755)
        else: #目前只处理 CMakeLists.txt 和 configure
            self.output.error("CMakeLists.txt exists: No")
            self.output.error("configure exists: No")
            self.build_mode = str(self.options.usr_mode)
            self.output.info("build_mode = " + self.build_mode)
            # raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")    
